//
//  JKMessageViewController.swift
//  afanti
//
//  Created by albert on 16/4/16.
//  Copyright © 2016年 albert. All rights reserved.
//

import UIKit

class JKMessageViewController: UIViewController {
    
    //标题栏
    var titView = UIView()
    //选中的标签按钮
    var selectedButton = UIButton()
    //底部绿色横线指示器
    var indiView = UIView()
    //scrollView
    var contView = UIScrollView()
    //标题栏的子控件
    var titSubviews:[AnyObject] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        //初始化导航栏
        view.backgroundColor = UIColor.init(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1)
        
        let rightItem = UIBarButtonItem(image: UIImage(named: "ic_more"), style: UIBarButtonItemStyle.Plain, target: self, action: "moreClick")
        self.navigationItem.rightBarButtonItems = [rightItem]
        
        //初始化子控制器
        setupChildVces()
        
        //设置scrollView
        setupTitlesView()
        
        //设置标题栏
        setupContentView()
        
        //监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "popoverClick:", name: JKPopoverdidSelectNotification, object: nil)
    }
    
    /** 监听通知 */
    func popoverClick(noti: NSNotification){
        let index = Int((noti.userInfo![JKPopDidSelectIndexKey]?.intValue)!)
        
        switch index{
        case 0: //点击了全部已读
            allRead()
            //break
            
        case 1: //点击了全部删除
            allDelete()
            //break
            
        default:
            print("other")
            //break
        }
    }
    
    deinit{
        /** 移除通知 */
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /** 全部已读 */
    func allRead(){
        print("全部已读")
        
        //判断无消息后，弹窗
        alert()
    }
    
    /** 全部删除 */
    func allDelete(){
        print("全部删除")
        
        //判断无消息后，弹窗
        alert()
    }

    /** 弹窗 */
    func alert(){
        if #available(iOS 8.0, *) {
            let alert = UIAlertController(title: nil, message: "暂无消息", preferredStyle: UIAlertControllerStyle.Alert)
            
            alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil))
            
            self.presentViewController(alert, animated: true, completion: nil)
            
        } else {
            let alert7 = UIAlertView(title: nil, message: "暂无消息", delegate: nil, cancelButtonTitle: "确定")
            alert7.show()
            
        }
    }
    
    //MARK: - 初始化子控制器
    func setupChildVces(){
        let answerMe = JKBaseViewController()
        answerMe.title = "回答我的"
        answerMe.labelText = "求助的问题被回答时，才会收到消息哦"
        self.addChildViewController(answerMe)
        
        let askMe = JKBaseViewController()
        askMe.title = "追问我的"
        askMe.labelText = "回答的问题被追问时，才会收到消息哦"
        askMe.btnText = "回答问题>>"
        askMe.delegate = self
        self.addChildViewController(askMe)
        
        let sysMessage = JKBaseViewController()
        sysMessage.title = "系统消息"
        sysMessage.labelText = "暂时没有消息"
        self.addChildViewController(sysMessage)
    }
    
    //MARK: - 设置scrollView
    func setupContentView(){
        //不要自动调整inset
        self.automaticallyAdjustsScrollViewInsets = false
        
        //创建scrollView
        let contentView = UIScrollView()
        
        //要设置frame和控制器的view同样大小
        contentView.frame = self.view.bounds;
        
        //    //设置内容间距，上99（64+35），下49间距（tabBar的高度是49）
        //    CGFloat topInset = CGRectGetMaxY(self.titlesView.frame);
        //    CGFloat bottomInset = self.tabBarController.tabBar.height;
        //    contentView.contentInset = UIEdgeInsetsMake(topInset, 0, bottomInset, 0);
        contentView.contentSize = CGSize(width: contentView.width * CGFloat(self.childViewControllers.count), height: 0)
        
        //添加到view,这样写会遮挡住标签栏
        //[self.view addSubview:contentView];
        //改为添加到view的最底部
        view.insertSubview(contentView, atIndex: 0)
        
        //隐藏底部滚动条
        contentView.showsHorizontalScrollIndicator = false;
        //分页效果
        contentView.pagingEnabled = true;
        //设置代理
        contentView.delegate = self;
        
        contView = contentView;
        
        scrollViewDidEndScrollingAnimation(contentView)
    }
    
    
    //MARK: - 设置标题栏
    func setupTitlesView(){
        
        //盛放顶部标签的view
        let titlesView = UIView()
        titlesView.width = view.width
        titlesView.height = 35
        titlesView.y = 64
        
        //设置颜色透明colorWithAlphaComponent，不要设置view的alpha，否则view的所有子控件都会透明
        titlesView.backgroundColor = UIColor.whiteColor()
        
        view.addSubview(titlesView)
        
        titView = titlesView
        
        //按钮下面的绿色指示器
        let indicatorView = UIView()
        indicatorView.backgroundColor = UIColor(red: 57/255.0, green: 164/255.0, blue: 83/255.0, alpha: 1)
        indicatorView.height = 2;
        indicatorView.y = titlesView.height - indicatorView.height;
        
        //顶部标题按钮
        //使用数组存放标签的文字，这样设置按钮文字的时候，可以直接按顺序从数组取出
        //    NSArray *titles = @[@"全dddd部", @"视频", @"图片", @"声音", @"段子"];
        for i in 0..<self.childViewControllers.count {
            
            let button = UIButton(type: UIButtonType.Custom)
            button.height = titlesView.height
            button.width = titlesView.width / CGFloat(childViewControllers.count)
            button.x = CGFloat(i) * button.width
            
            //设置文字
            button.setTitle(self.childViewControllers[i].title, forState: UIControlState.Normal)
            
            
            //设置普通和选中状态的文字颜色
            button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor(red: 0/255.0, green: 154/255.0, blue: 49/255.0, alpha: 1), forState: UIControlState.Selected)
            
            //设置字体大小
            button.titleLabel!.font = UIFont.systemFontOfSize(14)
            
            //注册点击事件
            button.addTarget(self, action: "titleClick:", forControlEvents: UIControlEvents.TouchUpInside)
            //绑定tag
            button.tag = i;
            
            titView.addSubview(button)
            
            titSubviews.append(button)
            
            //默认选中第一个
            if (i == 0) {
                //如果选择调用点击按钮的方法的话，一开始第一个按钮下面的绿色指示器会有动画
                
                //所以直接设置号第一个按钮。要让button的frame有值,才能给绿色指示器的宽度赋值
                // 1、让titlesView立即布局子控件
                //[titlesView layoutIfNeeded];
                // 2、也可以让按钮的label适应尺寸
                //[button.titleLabel sizeToFit];
                //然后给宽度赋值
                //self.indicatorView.width = button.titleLabel.width;
                
                //也可以直接计算按钮文字所占的宽度
                //indicatorView.width = [[self.childViewControllers[i] title] sizeWithAttributes:@{NSFontAttributeName : button.titleLabel.font}].width;
                let str = self.childViewControllers[i].title
                //var rect:CGRect = str.boundingRectWithSize(size, options: option, attributes: attributes, context: nil)
                indicatorView.width = str!.sizeWithAttributes([NSFontAttributeName : button.titleLabel!.font]).width
                
                
                indicatorView.centerX = button.centerX;
                button.selected = true
                selectedButton = button;
            }
        }
        
        //后添加绿色指示器,保证按钮在子控件数组的前面
        titlesView.addSubview(indicatorView)
        
        //将indicatorView赋值给属性
        indiView = indicatorView;

    }
    
    //MARK: - 点击标题
    func titleClick(button: UIButton){
        //如果点击的是相同的按钮，刷新，返回
        if selectedButton == button {
            return;
        }
        
        //设置选中状态
        selectedButton.selected = false
        button.selected = true
        selectedButton = button
        
        //动画显示底部绿色指示器
        UIView.animateWithDuration(0.25) { () -> Void in
            //宽度等于按钮label的宽度
            self.indiView.width = button.titleLabel!.width;
            
            //中心点x值相等
            //这里就不需要设置了，滑动的时候会设置
            //self.indicatorView.centerX = button.centerX;
        }
        
        
        //scrollView滚动
        var offset = contView.contentOffset;
        offset.x = CGFloat(button.tag) * contView.width;
        contView.setContentOffset(offset, animated: true)
    }
    
    /** 点击更多 */
    func moreClick(){
        print("更多")
        JKPopoverTool.show(["全部已读", "全部删除"], imageNames: ["ic_quanxuan", "ic_delet"], highImageNames: [], popFrame: CGRect(x: view.width - 115 - 2, y: 65, width: 115, height: 60), rowHeight: 30)
    }
}

extension JKMessageViewController: UIScrollViewDelegate, JKBaseViewControllerDelegate{
    //called when setContentOffset/scrollRectVisible:animated: finishes. not called if not animating
    func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
        //当前的索引
        let index: Int = Int(scrollView.contentOffset.x / scrollView.width)
        
        //取出子控制器
        let vc = self.childViewControllers[index];
        //设置x值才能滑动后显示出来，否则默认所有view的x = 0;
        vc.view.x = scrollView.width * CGFloat(index)
        //不设置y值的话，默认y = 20;
        vc.view.y = 0;
        //不设置高度的话，高度默认是屏幕高度 - 20;
        vc.view.height = scrollView.height;
        
        //    //最好写在tableViewController内部
        //    //设置内容间距，上99（64+35），下49间距（tabBar的高度是49）
        //    CGFloat topInset = CGRectGetMaxY(self.titlesView.frame);
        //    CGFloat bottomInset = self.tabBarController.tabBar.height;
        //    vc.tableView.contentInset = UIEdgeInsetsMake(topInset, 0, bottomInset, 0);
        
        //添加子控制器的view
        scrollView.addSubview(vc.view)
    }
    
    //scrollView停止减速（滚动）的时候调用，只有这个才能实现滚动切换
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //调用scrollViewDidEndScrollingAnimation方法
        scrollViewDidEndScrollingAnimation(scrollView)
        
        //获取索引
        let index: Int = Int(scrollView.contentOffset.x / scrollView.width)
        
        //这样写要保证按钮是先添加上去的
        //调用这个方法会出现一些问题。处在第一个tableView向右划，也会下拉刷新
        //[self titleClick:self.titlesView.subviews[index]];
        selectedButton.selected = false;
        selectedButton = titSubviews[index] as! UIButton
        selectedButton.selected = true;
        
        //动画显示底部绿色指示器
        UIView.animateWithDuration(0.25) { () -> Void in
            //宽度等于按钮label的宽度
            self.indiView.width = self.selectedButton.titleLabel!.width
            //设置中心点x值，不能省
            self.indiView.centerX = self.selectedButton.centerX
        }
        
    }
    
    //只要scrollView滚动就会调用这个方法
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //按钮的宽度
        let buttonWidth = selectedButton.width;
        
        //scrollView已经偏移的x值 / 能移动的总宽度（取值为0~0.8）
        let totalScale = scrollView.contentOffset.x / scrollView.contentSize.width;
        
        //设置中心点x值 = 起始位置x值 + 标签栏view总宽度 * 上面的比例
        indiView.centerX =  buttonWidth * 0.5 + (titView.width) * totalScale;
        
        
        //两个tableView之间偏移的比例
    }
    
    /** 跳转到答题广场 */
    func baseViewControllerDidClickAnswer(baseViewController: JKBaseViewController, button: UIButton) {
        self.tabBarController?.selectedIndex = 1
    }
}
